package com.itqf.proxy.dynimic_proxy2.factory;

import com.itqf.proxy.dynimic_proxy2.ProductService;
import com.itqf.proxy.dynimic_proxy2.impl.ProductServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/9/28
 * @Time: 下午5:20
 */

 class  MyInvocationHandler implements InvocationHandler {
     ProductService productService = null;
     //参数是：被代理对象
     public  MyInvocationHandler( ProductService productService){
        this.productService = productService;
     }

    /**
     * This method will be invoked on an invocation handler
     *      * when a method is invoked on a proxy instance that it is
     *      * associated with.
     * @param proxy   创建的代理对象
     * @param method   目标的方法（被代理的方法）
     * @param args      被代理的方法的参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
         System.out.println("开启事务");
         //connection.setAutoCommit(false);
        //调用目标方法
        try {
            Object result = method.invoke(productService, args);
            System.out.println("提交事务");//connection.commit();
            return result;
        }catch (Exception result){
            System.out.println("回滚事务");//connection.rollback();

        }
       return  null;
    }
}

public class MyServiceProxyFactory {


    public  static ProductService createProxyService(){
        //1,创建被代理对象
        ProductService productService = new ProductServiceImpl();
        //2,创建代理对象
      return (ProductService) Proxy.newProxyInstance(productService.getClass().getClassLoader(),
                productService.getClass().getInterfaces(),new MyInvocationHandler(productService) );



    }


}
